package com.dominator.utils.sms;

import com.dominFramework.core.typewrap.Dto;
import com.dominator.utils.api.ApiUtils;
import com.dominator.utils.dao.RedisUtil;
import com.dominator.utils.exception.ApiException;
import com.dominator.utils.network.HttpPoster;
import com.dominator.utils.system.Constants;
import com.dominator.utils.system.PropertiesLoader;
import com.dominator.utils.system.RedisTimeConstant;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class YunPianSmsUtils {
    
    private static final Logger log = LoggerFactory.getLogger(YunPianSmsUtils.class);

    public static PropertiesLoader propertiesLoader = new PropertiesLoader("sysconfig.properties");

    private static String ApiKey = propertiesLoader.getProperty("ApiKey");

    private static final String KEY = "CheckMessage";

    private static final String TimeKey = "CheckMessage:Time";

    private static RedisUtil jedis = RedisUtil.getRu();
    /**
     * 验证短信验证码
     */
    public static void checkcode(Dto dto) {
        String phone = dto.getString("phone_num");
        String usercode = dto.getString("usercode");
        Map<String, String> map = new HashMap<String, String>();
        // msg.setData("短信验证码错误");
        //

        String code = jedis.get(KEY + phone);
        if (jedis.exists(KEY + phone)) {//redis中有值ֵ
            if (StringUtils.isNotEmpty(code)) {
                if (!usercode.equals(code)) {//是否用户填入的验证码和缓存中的验证码一致
                    throw new ApiException(Constants.CODE_CHECK_MSG_ERROR, Constants.MSG_CHECK_MSG_ERROR);
                }
            }
        } else {//表示redis中没有值，即已经过期
            throw new ApiException(Constants.CODE_CHECK_PASS_ERROR, Constants.MSG_CHECK_PASS_ERROR);
        }
    }


    /**
     * 发送短信验证码
     *
     * @throws ApiException
     */

    public static void sendYPSms(Dto dto) throws ApiException {

        String mobile = dto.getString("phone_num");
        String phone = mobile;
        //检查手机号是否符合格式
        if (!ApiUtils.isMobile(phone))
        {//表示手机号码不匹配
            throw new ApiException(Constants.CODE_SEND_PHONE_ERROR, Constants.MSG_SEND_PHONE_ERROR);
        }

        //获取缓存中的上次访问时间
        String time0 = jedis.get(TimeKey);

        long now = System.currentTimeMillis();
        if (time0 != null && !time0.equals("nil"))

        {//表示redis中有值
            long lasttime = Long.parseLong(time0);
            if (now - lasttime < 60000) {//上次访问时间跟这次访问时间要大于60s
                throw new ApiException(Constants.CODE_SEND_LIMIT, Constants.MSG_SEND_LIMIT_ERROR);
            }
        }

        String text = ApiUtils.CreateRandom();
        //将随机生成的6个数放入到redis中
        jedis.setex(KEY + phone, text, RedisTimeConstant.Month);
        //初始化client,apikey作为所有请求的默认值(可以为空)
        YunpianClient clnt = new YunpianClient(
                ApiKey).init();
        /*Dto dto1 = new HashDto();
        dto1.put("code",text);*/
        String tpl_content = null;
        try {
            tpl_content = new String(propertiesLoader.getProperty("YZM").getBytes("ISO-8859-1"), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new ApiException(Constants.CODE_SEND_MSG_ERROR, Constants.MSG_SEND_MSG_ERROR);
        }
        // String tpl_content = propertiesLoader.getProperty("YZM");
        String value = tpl_content.replace("#code#",text);
        //String value = getcontent(dto1, tpl_id);
        //修改账户信息API
        Map<String, String> param = clnt.newParam(2);
        param.put(YunpianClient.MOBILE, mobile);
        param.put(YunpianClient.TEXT, value);
        Result<SmsSingleSend> r = clnt.sms().single_send(param);
        //账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*
        //获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
        log.info("返回码描述:" + r.getMsg());
        String time = String.valueOf(System.currentTimeMillis());
        String code = r.getCode().toString();
        if (code.equals("0"))

        {
            jedis.setex(TimeKey, time, RedisTimeConstant.Minute);
        }
        //最后释放client
        clnt.close();
        if (code.equals("0"))

        {//表示验证码短信发送成功
            log.info("验证码短信发送成功");
        } else

        {
            throw new ApiException(Constants.CODE_SEND_MSG_ERROR, Constants.MSG_SEND_MSG_ERROR);
        }


    }

    /**
     * 发送通知短信
     *
     * @throws ApiException
     */

    public static void sendNoticeSms(Dto dto) throws ApiException {
        System.out.println("YUNPIAN发送短信开始");
        String mobile = dto.getString("phone_num");
        String tpl_id = "";
        String tpl_content = "";
        switch (dto.getInteger("stype")) {
            case 1:
                tpl_id = propertiesLoader.getProperty("ZDNOT");
                break;
            case 2:
                tpl_id = propertiesLoader.getProperty("ZDYES");
                break;
            case 3:
                tpl_id = propertiesLoader.getProperty("BXNOT");
                break;
            case 4:
                tpl_id = propertiesLoader.getProperty("BXRDOING");
                break;
            case 5:
                tpl_id = propertiesLoader.getProperty("BXSDOING");
                break;
            case 6:
                tpl_id = propertiesLoader.getProperty("BXYES");
                break;
            case 7:
                tpl_id = propertiesLoader.getProperty("FKYES");
                break;
            case 8:
                tpl_id = propertiesLoader.getProperty("FKGQ");
                break;
        }
        YunpianClient clnt = new YunpianClient(
                ApiKey).init();
        //String sendSms = sendSms(ApiKey);
        String value = getcontent(dto,tpl_id);;
        //修改账户信息API
        Map<String, String> param = clnt.newParam(2);
        param.put(YunpianClient.MOBILE, mobile);
        param.put(YunpianClient.TEXT, value);
        Result<SmsSingleSend> r = clnt.sms().single_send(param);
        //账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*
        //获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
        log.info("返回码描述:" + r.getMsg());
        String time = String.valueOf(System.currentTimeMillis());
        String code = r.getCode().toString();
        //最后释放client
        clnt.close();
    }

    /**
     * 根据传入的参数生成不同的短信信息
     * @param dto
     * @param tpl_id
     * @return
     */
    public static String getcontent(Dto dto, String tpl_id)throws ApiException {
        String value = "";
        try {
            if (StringUtils.isNotEmpty(ApiKey)) {
                String sendSms = getTpl(ApiKey,tpl_id);
                ObjectMapper mapper = new ObjectMapper();
                JsonNode node = mapper.readTree(sendSms);
                JsonNode readTree = mapper.readTree(node.get("template").toString());
                String str = readTree.get("tpl_content").toString();
                for(String s : dto.keySet()){
                    String s0 = "#"+s+"#";
                    String s1 =      dto.getString(s);
                    str = str.replace("#"+s+"#",dto.getString(s));
                }
               // value = str.replace("#month#", month).replace("#money#",money);
                value = str.substring(1, str.length() - 1);
            }
        } catch (Exception e) {
            throw new ApiException(Constants.CODE_SMS_SEND_ERROR, Constants.MSG_SMS_SEND_ERROR);
        }
        return value;
    }

    /**
     * 根据用户标识和用户唯一id来获取短信模版
     * @param apikey
     * @return
     * @throws IOException
     */
    public static String getTpl(String apikey,String tpl_id) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("tpl_id", tpl_id);
        String rel = "";
        try {
             rel = HttpPoster.post("https://sms.yunpian.com/v1/tpl/get.json", params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  rel;
    }


   public static void main(String[] args) {
       jedis.setex(KEY + "17621501628", "123456", RedisTimeConstant.Month);

   }
   
}
